package com.yyb.sync;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yyb.domain.SysLoginInfo;
import com.yyb.service.SysLoginInfoService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * 描述: [保存日志的异步处理类]
 * 
 * 
 */
@Component
@Async
@EnableAsync
@Log4j2
public class AsyncSysLoginLogInfoService {
    @Resource
    private SysLoginInfoService sysLoginInfoService;

    private RestTemplate restTemplate=new RestTemplate();

    /**
     * 保存登录日志
     */
    public void saveLoginInfo(SysLoginInfo sysLoginInfo){
        String ipAddr = sysLoginInfo.getIpAddr();
        //处理IP地址
        if(StringUtils.hasText(ipAddr)){
            if(ipAddr.equals("127.0.0.1")||ipAddr.equalsIgnoreCase("localhost")){
                sysLoginInfo.setLoginLocation("本机");
            }else{
                /**
                 // http://ip-api.com/json/123.123.123.123?lang=zh-CN
                 {
                 "status": "success",
                 "country": "中国",
                 "countryCode": "CN",
                 "region": "BJ",
                 "regionName": "北京市",
                 "city": "北京",
                 "zip": "",
                 "lat": 39.911,
                 "lon": 116.395,
                 "timezone": "Asia/Shanghai",
                 "isp": "China Unicom Beijing Province Network",
                 "org": "",
                 "as": "AS4808 China Unicom Beijing Province Network",
                 "query": "123.123.123.123"
                 }
                 */
                try {
                    String ipCheckUrl="http://ip-api.com/json/%s?lang=zh-CN";
                    String relUrl=String.format(ipCheckUrl,ipAddr);
                    String json = restTemplate.getForObject(relUrl, String.class);
                    JSONObject jsonObject= JSON.parseObject(json);
                    if(jsonObject.getString("status").equals("success")){
                        String country = jsonObject.getString("country");
                        String regionName = jsonObject.getString("regionName");
                        String city = jsonObject.getString("city");
                        sysLoginInfo.setLoginLocation(country+" "+regionName+" "+city);
                    }
                }catch (Exception e){
                    log.info("IP查询失败,{}",ipAddr);
                    e.printStackTrace();
                }
            }
        }else{
            sysLoginInfo.setLoginLocation("未知");
        }
        this.sysLoginInfoService.insertSelective(sysLoginInfo);
    }

}
